package com.redhat.auth.log.parse;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.redhat.auth.log.annotation.ValueType;
import com.redhat.auth.log.common.RecordValueBean;

/**
 * 本类是根据用户的定义，分析出是否需要查出关联属性
 * @author lingen.liu
 *
 */
public class CascadeParse {
	
	public static  List<String> initValueBeanCascade(Class classType,List<RecordValueBean> recordBeans){
		List<String> cascadeList = new ArrayList<String>();
		for(RecordValueBean recordValue:recordBeans){
			if((recordValue.getValueType().equals(ValueType.beforeValue) || recordValue.getValueType().equals(ValueType.afterValue)) && recordValue.getExpr().contains(classType.getSimpleName())){
				String propertie = isCascade(classType,recordValue);
				if(propertie!=null)cascadeList.add(propertie);
			}
		}
		return cascadeList;
	}
	
	private static String isCascade(Class classType,RecordValueBean recordBean){
		String expr[] = recordBean.getExpr().split("\\.");
		if(expr.length>=2 && expr[0].equals(classType.getSimpleName())){
			String propertie = expr[1];
			if(isDataCascade(classType,propertie)) return propertie;
		}
		return null;
	}
	
	private static boolean isDataCascade(Class classType,String properties){
		try {
			Field field = classType.getField(properties);
			if(field.getAnnotation(OneToOne.class)!=null || field.getAnnotation(ManyToOne.class)!=null || field.getAnnotation(OneToMany.class)!=null ||  field.getAnnotation(ManyToMany.class)!=null){
				return true;
			}
			String methodName = "get"+properties.substring(0,1).toUpperCase()+properties.substring(1);
			Method method = classType.getMethod(methodName, null);
			if(method.getAnnotation(OneToOne.class)!=null || method.getAnnotation(ManyToOne.class)!=null || method.getAnnotation(OneToMany.class)!=null ||  method.getAnnotation(ManyToMany.class)!=null){
				return true;
			}
		}catch (Exception e) {
		  return false;
		}
		return false;
	}
}
